package com.zzyl.service.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.exception.BaseException;
import com.zzyl.service.WechatService;
import com.zzyl.utils.ObjectUtil;
import com.zzyl.utils.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author sjqn
 */
@Service
public class WechatServiceImpl implements WechatService {

    // 登录
    private static final String REQUEST_URL = "https://api.weixin.qq.com/sns/jscode2session";

    // 获取token
    private static final String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";

    // 获取手机号
    private static final String PHONE_REQUEST_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";

    @Value("${zzyl.wechat.appId}")
    private String appId;

    @Value("${zzyl.wechat.appSecret}")
    private String secret;


    /**
     * 获取openid
     *
     * @param code 登录凭证
     * @return
     * @throws IOException
     */
    @Override
    public String getOpenid(String code) {
        //封装参数
        Map<String,Object> requestUrlParam = getAppConfig();
        requestUrlParam.put("js_code",code);
        requestUrlParam.put("grant_type","authorization_code");

        String result = HttpUtil.get(REQUEST_URL, requestUrlParam);

        JSONObject jsonObject = JSONUtil.parseObj(result);
        // 若code不正确，则获取不到openid，响应失败
        if (ObjectUtil.isNotEmpty(jsonObject.getInt("errcode"))) {
            throw new RuntimeException(jsonObject.getStr("errmsg"));
        }

        return jsonObject.getStr("openid");
    }

    /**
     * 封装公共参数
     * @return
     */
    private Map<String, Object> getAppConfig() {
        Map<String, Object> requestParam = new HashMap<>();
        requestParam.put("appid",appId);
        requestParam.put("secret",secret);
        return requestParam;
    }


    @Override
    public String getPhone(String phoneCode) {
        //获取access_token
        String url = PHONE_REQUEST_URL+getAccessToken();

        Map<String,Object> requestParam = new HashMap<>();
        requestParam.put("code",phoneCode);

        String result = HttpUtil.post(url, JSONUtil.toJsonStr(requestParam));
        JSONObject jsonObject = JSONUtil.parseObj(result);
        if (jsonObject.getInt("errcode") != 0) {
            //若code不正确，则获取不到phone，响应失败
            throw new RuntimeException(jsonObject.getStr("errmsg"));

        }
        return jsonObject.getJSONObject("phone_info").getStr("purePhoneNumber");

    }

    public String getAccessToken(){
        Map<String, Object> requestParam = getAppConfig();
        requestParam.put("grant_type","client_credential");

        String result = HttpUtil.get(TOKEN_URL, requestParam);
        //解析
        JSONObject jsonObject = JSONUtil.parseObj(result);

        String accessToken = jsonObject.getStr("access_token");
        if(StringUtils.isEmpty(accessToken)){
            throw new RuntimeException("token为空");
        }
        return accessToken;
    }
}